import { createStore } from 'vuex'

export default createStore({
  state: {
    count: 0,
    // 确保获取的值是 string 类型，如果为 null 则设置为 null
    userInfo: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user') as string) : null,
    // 从localStorage加载token，如果没有，则设置为空字符串
    token: localStorage.getItem('token') || '',
    todos: []
  },
  getters: {
    // 判断用户是否已登录（有 token）
    isLoggedIn: state => !!state.token,
    getToken: state => state.token
  },
  mutations: {
    SET_COUNT(state, payload) {
      state.count = payload
    },
    SET_USER(state, user) {
      state.userInfo = user
      console.log(`output->user`, user)
      localStorage.setItem('user', JSON.stringify(user)) // 持久化到localStorage
    },
    REMOVE_USER(state) {
      state.userInfo = null
      localStorage.removeItem('user') // 删除localStorage中的用户信息
    },
    // 存储 token
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token) // 持久化到localStorage
    },
    // 清除 token
    REMOVE_TOKEN(state) {
      state.token = ''
      localStorage.removeItem('token') // 删除localStorage中的token
    }
  },
  actions: {
    // 异步设置 token
    async saveToken({ commit }, token) {
      commit('SET_TOKEN', token)
    },
    // 退出登录
    async logout({ commit }) {
      commit('REMOVE_TOKEN')
      commit('REMOVE_USER') // 清空用户信息
    }
  },
  modules: {
  }
})
